#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
//匿名管道
int main()
{
    int pipe_fd[2] = {0};
    //pipe_fd[0] 是读  pipe_fd[1]是写
    if(pipe(pipe_fd) < 0)
    {
        printf("创建匿名管道失败\n");
        exit(1);
    }
    //以子进程写，父进程读为例子
    int id = fork();
    if(id == 0)
    {
        close(pipe_fd[0]);
        int count = 5;
        while(count--)
        {
            
            const char* msg = "Mango-C++";
            write(pipe_fd[1],msg,strlen(msg));//细节：写入strlen(msg)字节，因为\0只是C语言的结束标识符
            sleep(1);
        }
        close(pipe_fd[1]);//最后关闭子进程的写端
        exit(0);
    }
    //parent
    close(pipe_fd[1]);
#define SIZE 1024
    while(1)
    {
        sleep(1);
        char buffer[SIZE] = {0};
        ssize_t n = read(pipe_fd[0],buffer,SIZE-1);
        if(n == 0)
        {
            printf("对端关闭\n");
            break;
        }
        else if(n < 0)
        {
            printf("n :%d ",(int)n);
            printf("read error\n");
            break;
        }
        else
        {
            printf("n :%d ",(int)n);
            buffer[n] = 0;
            printf("读取的内容为：%s\n",buffer);
        }
    }
    close(pipe_fd[0]);

    int status = 0;
    waitpid(-1,&status,0);
    printf("退出码：%d  收到信号：%d\n",(status>>8)&0xff,status&0x7f);
    return 0;
}